package com.taomeng.servlet;

import com.taomeng.constant.LeaveTypeConstant;
import com.taomeng.entity.LeaveApplication;
import com.taomeng.entity.Student;
import com.taomeng.entity.User;
import com.taomeng.service.LeaveService;
import com.taomeng.service.StudentService;
import com.taomeng.util.DateUtils;
import com.taomeng.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/public/*")
public class PublicServlet extends BaseServlet {
    @Autowired
    private StudentService studentService;
    @Autowired
    private LeaveService leaveService;

    public void account(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 2）获取当前的 Subject. 调用 SecurityUtils.getSubject();
        Subject currentUser = SecurityUtils.getSubject();
        // 3）测试当前的用户是否已经被认证. 即是否已经登录. 调用 Subject 的 isAuthenticated()
        if (!currentUser.isAuthenticated()) {
            // 4）若没有被认证, 则把用户名和密码封装为 UsernamePasswordToken 对象
            UsernamePasswordToken upt = new UsernamePasswordToken(username, password);
            // 5）执行登录: 调用 Subject 的 login(AuthenticationToken) 方法.
            try {
                currentUser.login(upt);
                if (username.trim().length() == 9) {
                    Student principal = (Student) currentUser.getPrincipal();
                    currentUser.getSession().setAttribute("loginUser", principal);
                    req.getSession().setAttribute("name", principal.getName());
                    req.getSession().setAttribute("studentNum", principal.getNum());
                    resp.sendRedirect("/index.jsp");
                } else {
                    //用户登录成功后，要存放用户到Session
                    User principal = (User) currentUser.getPrincipal();
                    UserContext.setUser(principal);
                    req.getSession().setAttribute("name", principal.getName());
                    resp.sendRedirect("/admin/public/main.jsp");
                }
            } catch (AuthenticationException | IOException e) {
                e.printStackTrace();
                resp.sendRedirect("/admin/login.jsp");
            }
        } else {
            resp.sendRedirect("/admin/public/main.jsp");
        }
    }

    public void index(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.sendRedirect("/admin/public/main.jsp");
    }

    public void leave(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int leaveType = Integer.parseInt(req.getParameter("leaveType"));

        String studentNum = req.getParameter("studentNum");
        Map<String, Object> data = studentService.findAllInfoByStudentNum(studentNum);
        data.put("type", leaveType);
        data.put("applicationTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm"));

        req.setAttribute("currentStatus", "学生申请");
        req.setAttribute("data", data);
        req.getRequestDispatcher("/include/leave.jsp").forward(req, resp);
    }

    public void shiwu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student student = (Student) SecurityUtils.getSubject().getPrincipal();
        List<LeaveApplication> applicationList = leaveService.findApplicationByStudentId(student.getId());
        List<LeaveApplication> backlogApplication = leaveService.findBacklogApplication(student.getId());

        req.setAttribute("allApplication", applicationList);
        req.setAttribute("backlogApplication", backlogApplication);
        req.getRequestDispatcher("/include/shiwu.jsp").forward(req, resp);

    }

    public void details(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        String studentNum = String.valueOf(req.getSession().getAttribute("studentNum"));
        Map<String, Object> map = leaveService.findApplicationInfoById(id, studentNum);

//        map.forEach((key,value)->System.out.println(key+"："+value));


        long begintime = DateUtils.parse(String.valueOf(map.get("begintime"))).getTime();
        long endtime = DateUtils.parse(String.valueOf(map.get("endtime"))).getTime();
        int status = Integer.parseInt(String.valueOf(map.get("status")) );
        long currentTime = new Date().getTime();
        System.out.println("begin:"+String.valueOf(map.get("begintime")));
        System.out.println("end:"+String.valueOf(map.get("endtime")));
        System.out.println("currentTime:"+DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));

        boolean enable = currentTime >= begintime && currentTime <= endtime && status == 2;

        req.setAttribute("currentStatus", "学生处理");
        req.setAttribute("enable", enable);
        req.setAttribute("data", map);
        req.getRequestDispatcher("/include/leave.jsp").forward(req, resp);
    }

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext application = this.getServletContext();
        // 解决servlet用@Autowired自动注入service失败的问题
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, application);
    }
}
